import cx from 'classnames'
import React, { CSSProperties } from 'react'
import { RenderInfo } from '../interfaces'
import { Classes } from '../styles'


export default function TableHeader({ info }: { info: RenderInfo }) {
  const { flat, stickyLeftMap, stickyRightMap } = info
  const rowCount = 1
  const headerRenderInfo = flat.full

  const fullFlatCount = flat.full.length
  const leftFlatCount = flat.left.length
  const rightFlatCount = flat.right.length

  const thead = headerRenderInfo.map((wrappedCols, level) => {
    const headerCells = () => {
      const col = wrappedCols
      const colIndex = level

        const headerCellProps = col.headerCellProps ?? {}

        const positionStyle: CSSProperties = {}
        if (level < leftFlatCount) {
          positionStyle.position = 'sticky'
          positionStyle.left = stickyLeftMap.get(colIndex)
        } else if (colIndex >= fullFlatCount - rightFlatCount) {
          positionStyle.position = 'sticky'
          positionStyle.right = stickyRightMap.get(colIndex)
        }

        return (
          <th
            key={colIndex}
            {...headerCellProps}
            className={cx(Classes.tableHeaderCell, headerCellProps.className, {
              first: colIndex === 0,
              last: colIndex === fullFlatCount,
              'lock-left': colIndex < leftFlatCount,
              'lock-right': colIndex >= fullFlatCount - rightFlatCount,
            })}
            rowSpan={rowCount - level}
            style={{
              textAlign: col.align,
              ...headerCellProps.style,
              ...positionStyle,
            }}
          >
            {col.title ?? col.name}
          </th>
        )
          }

    return (
      <>
        {headerCells()}
      </>
    )
  })

  return (
    <table>
      <colgroup>
        {headerRenderInfo.map((wrapped, index) => {
            return <col key={index} style={{ width: wrapped.width }} />
        })}
      </colgroup>
      <thead>
      <tr
        className={cx(Classes.tableHeaderRow, {
          first: true,
          last: true,
        })}
      >
        {thead}
        </tr>
      </thead>
    </table>
  )
}
